﻿#region License
// (c) Intergen.
// This source is subject to the Microsoft Public License (Ms-PL).
// Please see http://go.microsoft.com/fwlink/?LinkID=131993 for details.
// All other rights reserved.
#endregion

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;

namespace MediaWiki.Office.Packaging
{
  public class PackageRelationshipCollection : List<PackageRelationship>
  {
    private const string RelationshipsTagName = "Relationships";
    private const string RelationshipTagName = "Relationship";
    private const string TargetAttributeName = "Target";
    private const string TypeAttributeName = "Type";
    private const string IdAttributeName = "Id";
    private const string XmlBaseAttributeName = "xml:base";
    private const string TargetModeAttributeName = "TargetMode";

    private readonly IPackage _package;
    private readonly IPackagePart _sourcePart;

    public PackageRelationshipCollection(IPackage package, IPackagePart sourcePart)
    {
      if (package == null)
        throw new ArgumentNullException("package");

      _package = package;
      _sourcePart = sourcePart;

      Uri relationshipUri = PackageUriHelper.GetPartRelationshipUri((_sourcePart != null) ? _sourcePart.Uri : PackageUriHelper.PackageRootUri);
      string relationshipContent = package.GetContent(relationshipUri);

      IEnumerable<PackageRelationship> relationships = CreatePackageRelationships(relationshipContent);

      AddRange(relationships);
    }

    public IEnumerable<PackageRelationship> CreatePackageRelationships(string relationshipContent)
    {
      XElement document = XElement.Parse(relationshipContent);
      XNamespace ns = PackageRelationship.Namespace;

      var relationships = from r in document.Elements(ns + RelationshipTagName)
                          select CreatePackageRelationship(
                            r.Attribute(TargetAttributeName),
                            r.Attribute(TargetModeAttributeName),
                            r.Attribute(TypeAttributeName),
                            r.Attribute(IdAttributeName)
                            );

      return relationships;
    }

    public PackageRelationship CreatePackageRelationship(XAttribute targetAttribute, XAttribute targetModeAttribute, XAttribute relationshipTypeAttribute, XAttribute idAttribute)
    {
      TargetMode targetMode = TargetMode.Internal;
      if (targetModeAttribute != null)
        targetMode = (TargetMode)Enum.Parse(typeof(TargetMode), targetModeAttribute.Value, false);

      return new PackageRelationship(_package,
        _sourcePart,
        new Uri(targetAttribute.Value, UriKind.RelativeOrAbsolute),
        targetMode,
        relationshipTypeAttribute.Value,
        idAttribute.Value);
    }
  }
}